package com.webserver.servlet;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.FileTemplateResolver;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShowAllUserServlet extends HttpServlet {
    public void service(HttpRequest request, HttpResponse response){
        try(RandomAccessFile raf = new RandomAccessFile("./user.dat","rw");) {
            List<Map<String,String>>list = new ArrayList<>();
            for (int i =0;i<raf.length()/100;i++){
                Map<String,String>user = new HashMap<>();
                byte []data = new byte[32];
                raf.read(data);
                String username = new String(data,"utf-8").trim();

                raf.read(data);
                String password = new String(data,"utf-8").trim();

                raf.read(data);
                String nickname = new String(data,"utf-8").trim();

                int age = raf.readInt();
                user.put("username",username);
                user.put("password",password);
                user.put("nickname",nickname);
                user.put("age",age+"");
                list.add(user);
            }

            Context context = new Context();
            context.setVariable("users",list);

            FileTemplateResolver tr = new FileTemplateResolver();
            tr.setTemplateMode("html");
            tr.setCharacterEncoding("utf-8");

            TemplateEngine te = new TemplateEngine();
            te.setTemplateResolver(tr);

            String html = te.process("./webapps/myweb/userList.html",context);

            byte[]data = html.getBytes("utf-8");
            response.setData(data);
            response.putHeaders("Content-Type","text/html");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
